// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
zip.workerScriptsPath = "/lib/";

function fetchDianpingImage(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function(data) {
    if (xhr.readyState == 4) {
      if (xhr.status == 200) {
        callback(xhr.response);
      } else {
        callback(null);
      }
    }
  }
  // Note that any URL fetched here must be matched by a permission in
  // the manifest.json file!
  xhr.open('GET', url, true);
  xhr.responseType = "blob";
  xhr.send();
};

function pushBlob(index, environmentPhoto, callback, onend) {
  if(index < environmentPhoto.length) {
    fetchDianpingImage(environmentPhoto[index], function(blob){
      callback(blob);
      index++;
      pushBlob(index, environmentPhoto, callback, onend);
    });
  } else {
    onend();
  }
}

var model = (function() {
  var zipFileEntry, zipWriter, writer, creationMethod;

  return {
    setCreationMethod : function(method) {
      creationMethod = method;
    },
    addFiles : function addFiles(files, onend) {
        console.log("addFiles");
      var addIndex = 0;

      function nextFile() {
        var file = files[addIndex];
        console.log(file.name);
        console.log(file.blob);
        zipWriter.add(file.name, new zip.BlobReader(file.blob), function() {
          addIndex++;
          if (addIndex < files.length)
            nextFile();
          else
            onend();
        });
      }

      function createZipWriter() {
        console.log("addFiles init");
        zip.createWriter(writer, function(writer) {
          zipWriter = writer;
          nextFile();
        }, onerror);
      }
      console.log(zipWriter);
      if (zipWriter){
        nextFile();
      } else if (creationMethod == "Blob") {
        writer = new zip.BlobWriter();
        createZipWriter();
      } else {
        createTempFile(function(fileEntry) {
          zipFileEntry = fileEntry;
          writer = new zip.FileWriter(zipFileEntry);
          createZipWriter();
        });
      }
    },
		getBlobURL : function(callback) {
      zipWriter.close(function(blob) {
        var blobURL = creationMethod == "Blob" ? URL.createObjectURL(blob) : zipFileEntry.toURL();
        callback(blobURL);
        zipWriter = null;
      });
    },
    getBlob : function(callback) {
      zipWriter.close(callback);
    }
  };
})();

chrome.runtime.onMessage.addListener(function (result) {
  var infoBlob = new Blob([result.brandStory], {type : "text/plain"});
  var imageBlobs = [];
  var index = 0;
  pushBlob(
    index, result.environmentPhoto, 
    function(blob){
      imageBlobs.push(blob);
    },
    function(){
      model.setCreationMethod("Blob");
      var files = [];

      files.push({name:"0.txt", blob: infoBlob});

      for(var i=0;i<imageBlobs.length;i++) {
        console.log(imageBlobs[i]);
        files.push({name:(i+1)+".jpg", blob: imageBlobs[i]});
      }
      console.log(files);
      model.addFiles(files, function(){
        model.getBlobURL(function(blobURL) {
          console.log(blobURL);
          chrome.downloads.download({ url: blobURL, filename : result.shopName + ".zip" });
        });
      });
    }
  );
});

chrome.browserAction.onClicked.addListener(function(tab) {
  // No tabs or host permissions needed!
  chrome.tabs.executeScript({
    file: "/lib/jquery_1.7.1.js"
  });
  
  chrome.tabs.executeScript({
    file: "/script/content_script.js"
  });
});

/* 
function fetchDianpingImage(index, url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function(data) {
    if (xhr.readyState == 4) {
      if (xhr.status == 200) {
        callback(index, xhr.response);
      } else {
        callback(null);
      }
    }
  }
  // Note that any URL fetched here must be matched by a permission in
  // the manifest.json file!
  xhr.open('GET', url, true);
  xhr.responseType = "blob";
  xhr.send();
};

var environmentPhoto = ["http://p1.meituan.net/dpmerchantalbum/48a52bc57e611e45563b966a5ae66eca101957.jpg%40249w_249h_1e_1c_1l%7Cwatermark%3D1%26%26r%3D1%26p%3D9%26x%3D2%26y%3D2%26relative%3D1%26o%3D20",
"http://p0.meituan.net/dpmerchantalbum/88dc11c7026e5ea4b721c30c83bf56ee304300.jpg%40249w_249h_1e_1c_1l%7Cwatermark%3D1%26%26r%3D1%26p%3D9%26x%3D2%26y%3D2%26relative%3D1%26o%3D20",
"http://p0.meituan.net/ugcpic/220cec0b52a46843818faec4d82dfa14%40249w_249h_1e_1c_1l%7Cwatermark%3D1%26%26r%3D1%26p%3D9%26x%3D2%26y%3D2%26relative%3D1%26o%3D20",
"http://p0.meituan.net/ugcpic/37d7017b81f01bdc79c08d4ac23457fa%40249w_249h_1e_1c_1l%7Cwatermark%3D1%26%26r%3D1%26p%3D9%26x%3D2%26y%3D2%26relative%3D1%26o%3D20",
"http://p0.meituan.net/ugcpic/6f642c7e45812be52a7f680c8f65f735%40249w_249h_1e_1c_1l%7Cwatermark%3D1%26%26r%3D1%26p%3D9%26x%3D2%26y%3D2%26relative%3D1%26o%3D20"];

console.log(environmentPhoto);

var files = [];
var infoBlob = new Blob(["test"], {type : "text/plain"});

files.push({name:"0.txt", blob: infoBlob});
var index = 0;

fetchDianpingImage(environmentPhoto[index], function(index, blob){
  files.push({name: index+".jpg", blob: blob});
  index++;
  if(index < files.length) {
    fetchDianpingImage(environmentPhoto[index], 
  }
});

  model.setCreationMethod("Blob");
  model.addFiles(files, function(){
    model.getBlobURL(function(blobURL) {
        console.log(blobURL);
      chrome.downloads.download({ url: blobURL, filename : "test.zip" });
    });
  }); */
  // zipName = result.shopName + ".zip";

  
